/**********************************************************************
 *@Project： clouddemo
 *@File: AresSessionListener
 *@Date: 2017/4/17
 *@Copyright (C) 2013-2017 http://www.posun.cn. All Rights Reserved.
 ***********************************************************************
 *注意： 本内容仅限于深圳市普盛实业有限公司内部使用，禁止外泄
 **********************************************************************
 */
package com.posun.edu.system.config;

import com.posun.cloud.tracing.enums.LogType;
import com.posun.framework.Constants;
import com.posun.framework.cache.CacheUtil;
import com.posun.framework.log.AresLog;
import com.posun.framework.log.LogBuilder;
import com.posun.framework.util.DateUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;

import java.time.LocalTime;

/**
 * <p>
 * TODO<br>
 *
 * @author YL
 * @version 1.0
 * @createTime 2017/4/17 12:34
 * @ChangeLog
 */
public class AresSessionListener implements SessionListener {

    @Override
    public void onStart(Session session) {
        if (AresLog.isDebugEnabled(LogType.ACCESS)) {
            AresLog.debug(new LogBuilder(this.getClass(), LogType.ACCESS, "创建了一个Session连接:[" + session.getId() + "]"));
        }
        if (session.getAttribute(Constants.CURRENT_USER) != null) {
            setAllUserNumber(1);
        }
    }

    @Override
    public void onStop(Session session) {
        if (getAllUserNumber() > 0) {
            AresLog.debug(new LogBuilder(this.getClass(), LogType.ACCESS,
                    "销毁了一个Session连接:[" + session.getId() + "]，Session存活时间：" +
                            DateUtil.getDiffMinutes(LocalTime.now(),
                                    DateUtil.convertLocalTime(session.getStartTimestamp()))));
        }
        if (session.getAttribute(Constants.CURRENT_USER) != null) {
            session.removeAttribute(Constants.CURRENT_USER);
            setAllUserNumber(-1);
        }
    }

    @Override
    public void onExpiration(Session session) {
        if (AresLog.isDebugEnabled(LogType.ACCESS)) {
            AresLog.debug(new LogBuilder(this.getClass(), LogType.ACCESS, "session已失效，等待停止:[" + session.getId() + "]"));
        }
    }

    private void setAllUserNumber(int n) {
        String key = Constants.CACHE_NAMESPACE + "SESSION:LOCK";
        while (!CacheUtil.getLock(key)) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                AresLog.error(new LogBuilder(this.getClass(), LogType.DEBUG, e.getMessage(), e));
            }
        }
        try {
            Integer number = getAllUserNumber() + n;
            if (number >= 0) {
                AresLog.info(new LogBuilder(this.getClass(), LogType.ACCESS, "当前总用户数：" + number));
                CacheUtil.getCache().set(Constants.ALLUSER_NUMBER, number);
            }
        } finally {
            CacheUtil.unlock(key);
        }
    }

    /**
     * 获取在线用户数量
     */
    public static Integer getAllUserNumber() {
        Integer v = (Integer) CacheUtil.getCache().get(Constants.ALLUSER_NUMBER);
        if (v != null) {
            return v;
        }
        return 0;
    }
}
